﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aga.Diagrams.Tools;
using Aga.Diagrams;
using System.Windows;
using TestApp.Flowchart.Model;

namespace TestApp.Flowchart
{
    class DragDropTool : IDragDropTool
    {
        DiagramView _view;
        FlowchartModel _model;
        int _x, _y;

        public DragDropTool(DiagramView view, FlowchartModel model)
        {
            _view = view;
            _model = model;
        }

        public void OnDragEnter(System.Windows.DragEventArgs e)
        {
        }

        public void OnDragOver(System.Windows.DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;
            if (e.Data.GetDataPresent("System.String"))
            {
                var position = e.GetPosition(_view);
                _x = (int)(position.X / _view.GridCellSize.Width);
                _y = (int)(position.Y / _view.GridCellSize.Height);
                if (_y >= 0 && _x >= 0)
                    if (_model.Nodes.Where(p => p.Y == _y && p.X == _x).Count() == 0)
                        e.Effects = e.AllowedEffects;
            }
            e.Handled = true;
        }

        public void OnDragLeave(System.Windows.DragEventArgs e)
        {
        }

        public void OnDrop(System.Windows.DragEventArgs e)
        {
            var fullname = e.Data.GetData("System.String") as String;

            Type t = Type.GetType(fullname);
            var obj = t.Assembly.CreateInstance(fullname);

            var toolboxitem = Singleton.Instance().ToolBoxList.Single<ToolBoxItem>(x => x.FullName == fullname);


            int max_level = 0;
            if (_model.Nodes.Count > 0)
                max_level = _model.Nodes.Max(x => x.Level);

            var node = obj as FlowNode;
            node.Guid = Guid.NewGuid().ToString();
            node.FullName = fullname;
            node.X = _x;
            node.Y = _y;
            node.Height = 120;
            node.Width = 100;
            node.Text = toolboxitem.DisplayName;
            node.Level = max_level + 1;
            _model.Nodes.Add(node);


            Singleton.Instance().commandList.Add(new Command()
            {
                type = CommandEnum.Add,
                guid = node.Guid
            });

            e.Handled = true;
        }
    }
}
